import sys
import os
project_root = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, project_root)



from backup_restore_tool import DataBackupRestoreTool
from Progress_Tracking_CLI_DataPersistence.lms_main import LMS
from User_Management.data_persistence import load_users
from Course_Management_and_Enrollment.data_persistence import load_courses
from Assignment_and_Grading.data_persistence import DataPersistence


def sync_course_data():
    """同步课程数据,确保LMS实例和Course类的_all_courses列表保持一致"""
    try:
        from User_Management.user_classes import User
        from Course_Management_and_Enrollment.course_task_classes import Course
        
        print("正在同步课程数据...")
        
        # 创建LMS实例以获取课程数据
        lms = LMS()
        
        # 确保系统已初始化
        lms.initialize_system()
        
        # 获取LMS实例中的课程列表
        lms_courses = lms.courses
        
        # 获取Course类的_all_courses列表
        course_class_courses = Course._all_courses
        
        # 创建课程ID映射,便于快速查找
        lms_course_ids = {course.course_id: course for course in lms_courses}
        course_class_course_ids = {course.course_id: course for course in course_class_courses}
        
        # 同步逻辑:将LMS实例中的课程同步到Course._all_courses
        sync_count = 0
        for course_id, lms_course in lms_course_ids.items():
            if course_id not in course_class_course_ids:
                # 课程在LMS实例中但不在Course._all_courses中,添加进去
                Course._all_courses.append(lms_course)
                sync_count += 1
            else:
                # 课程已存在,检查状态是否一致
                course_class_course = course_class_course_ids[course_id]
                if course_class_course.status != lms_course.status:
                    # 更新状态
                    course_class_course.status = lms_course.status
                    sync_count += 1
        
        print(f"✅ 课程数据同步完成,同步了 {sync_count} 门课程")
        return True
        
    except Exception as e:
        print(f"❌ 课程数据同步失败: {str(e)}")
        return False


def main():
    """主程序入口"""
    print("Starting GT-OOP Learning Management System...")
    
    # 检查数据文件完整性并在需要时自动恢复
    data_file_path = os.path.join(project_root, "data.json")
    backup_tool = DataBackupRestoreTool(data_file_path)
    
    
    # 检查数据文件是否存在或损坏
    if not os.path.exists(data_file_path) or not backup_tool.verify_data_integrity():
        print("⚠️  Data file missing or corrupted. Attempting to restore from backup...")
        # 尝试从最新备份恢复
        backups = backup_tool.list_backups()
        if backups:
            # 自动使用最新的备份
            latest_backup = backups[0]
            print(f"Attempting to restore from latest backup: {latest_backup['filename']}")
            if backup_tool.restore_from_backup(latest_backup['filename']):
                print("✅ Data successfully restored from backup.")
                # 创建LMS实例
                lms = LMS()
            else:
                print("❌ Failed to restore data. Initializing with empty database.")
                # 创建LMS实例,不使用备份
                lms = LMS(use_backup=False)
        else:
            print("❌ No backup files found. Initializing with empty database.")
            # 创建LMS实例,不使用备份
            lms = LMS(use_backup=False)
    else:
        # 数据文件正常
        # 添加课程状态一致性检查
        print("正在检查课程状态一致性...")
        # 先确保用户数据已加载
        print("正在预加载用户数据...")
        from User_Management.data_persistence import load_users
        users = load_users()
        print(f"✅ 预加载了 {len(users)} 个用户")
        # 创建LMS实例
        # 创建LMS实例
        lms = LMS()
        
        # 执行课程数据同步
        sync_course_data()
    
    # 运行 CLI 界面
    try:
        lms.run_cli()
    except KeyboardInterrupt:
        print("\n\nSystem interrupted by user. Saving data...")
        lms.save_data()
        print("Goodbye!")
        sys.exit(0)
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        print("Saving data before exit...")
        lms.save_data()
        sys.exit(1)
